package com.cg.offer;

import org.junit.Test;

import java.util.Arrays;

/**
 * 剑指Offer 29.顺时针打印矩阵
 *
 * @program: LeetCode->Offer_29
 * @description: 剑指Offer 29.顺时针打印矩阵
 * @author: cg
 * @create: 2022-04-02 21:02
 **/
public class Offer_29 {

    @Test
    public void test29() {
        System.out.println(Arrays.toString(spiralOrder(new int[][]{
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}})));
    }

    /**
     * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
     * <p>
     * 示例 1：
     * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
     * 输出：[1,2,3,6,9,8,7,4,5]
     * <p>
     * 示例 2：
     * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
     * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
     * <p>
     * 限制：
     * 0 <= matrix.length <= 100
     * 0 <= matrix[i].length <= 100
     *
     * @param matrix
     * @return
     */
    public int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
        if (row == 0) {
            return new int[0];
        }
        int columns = matrix[0].length;
        int[] res = new int[row * columns];
        // 索引，左右上下边界
        int index = 0, left = 0, right = columns - 1, top = 0, bottom = row - 1;
        while (true) {
            // 从左往右
            for (int i = left; i <= right; i++) {
                res[index++] = matrix[top][i];
            }
            // 上边最后一层
            if (++top > bottom) {
                break;
            }
            // 从上往下
            for (int i = top; i <= bottom; i++) {
                res[index++] = matrix[i][right];
            }
            // 右边最后一列
            if (--right < left) {
                break;
            }
            // 从右往左
            for (int i = right; i >= left; i--) {
                res[index++] = matrix[bottom][i];
            }
            // 下边最后一层
            if (--bottom < top) {
                break;
            }
            // 从下往上
            for (int i = bottom; i >= top; i--) {
                res[index++] = matrix[i][left];
            }
            // 左边最后一列
            if (++left > right) {
                break;
            }
        }
        return res;
    }
}
